<template>
  <div class="detail">
    <h3>节目详情</h3>

    <div class="content-wrapper" :class="{ collapsed: isCollapsed }">
      <div class="content" v-html="content" ref="refContent"></div>
      <div class="gradient-overlay" v-if="isCollapsed && showToggleBtn"></div>
    </div>

    <div class="toggle-btn" v-if="showToggleBtn" @click="toggleContent">
      <van-icon :name="isCollapsed ? 'arrow-down' : 'arrow-up'" />
      <span>{{ isCollapsed ? '展开' : '收起' }}</span>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, toRefs, useTemplateRef, nextTick } from 'vue'
import { useRoute } from 'vue-router'
const route = useRoute()

const props = defineProps(['content'])
const { content } = toRefs(props)

//是否折叠
const isCollapsed = ref(true)
const showToggleBtn = ref(false)
const contentRef = useTemplateRef('refContent')
const originalHeight = ref(0)

// 切换内容显示状态
const toggleContent = () => {
  isCollapsed.value = !isCollapsed.value
}

// 检查内容高度，判断是否需要显示展开/收起按钮
const checkContentHeight = () => {
  nextTick(() => {
    if (contentRef.value) {
      const height = contentRef.value.clientHeight
      originalHeight.value = height

      // 如果内容高度超过300px，则显示展开/收起按钮
      if (height > 300) {
        showToggleBtn.value = true
        isCollapsed.value = true
      } else {
        showToggleBtn.value = false
        isCollapsed.value = false
      }
    }
  })
}

onMounted(() => {
  checkContentHeight()
})

// 监听内容变化，重新检查高度
defineExpose({
  refreshContentHeight: checkContentHeight,
})
</script>

<style lang="scss" scoped>
.detail {
  padding: 10px 15px 0;

  h3 {
    font-size: 20px;
    font-weight: 500;
    margin: 0;
  }

  .content-wrapper {
    position: relative;
    overflow: hidden;

    &.collapsed {
      max-height: 300px;
      overflow: hidden;
    }

    .content {
      font-size: 16px;

      // 处理图片宽度问题
      :deep(img) {
        max-width: 100%;
        height: auto;
        display: block;
        margin: 0 auto;
      }

      // 处理可能存在的其他宽度溢出元素
      :deep(*) {
        max-width: 100%;
      }
    }

    .gradient-overlay {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      height: 30px;
      background: linear-gradient(to bottom, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1));
    }
  }

  .toggle-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 15px 0;
    color: #ff1d41;
    font-size: 14px;
    cursor: pointer;

    span {
      margin-right: 5px;
    }
  }
}
</style>
